package com.example.springboot.biz;

import com.example.springboot.bean.User;
import com.example.springboot.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.validation.Errors;

import javax.annotation.Resource;

@Service
@Transactional(rollbackFor = BizException.class)
public class UserBiz {

    @Resource
    UserMapper um;

    public void reg(User user, Errors errors) throws BizException {
        if (errors.hasErrors() == false) {
            if (um.countByName(user.getName()) > 0) {
                errors.rejectValue("name", "NameDup...",
                        "该用户已经被注册!");
            } else {
                // 转成 MD5 密文
                String pwd = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
                user.setPwd(pwd);
                um.insert(user);
            }
        }

        if (errors.hasErrors()) {
            throw new BizException("注册失败!", errors.getAllErrors());
        }

    }

    public User login(User user, Errors errors) throws BizException {
        if (errors.hasFieldErrors("name") == false &&
                errors.hasFieldErrors("pwd") == false) {
            // MD5
            String pwd = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
            user.setPwd(pwd);
            User dbuser = um.selectByLogin(user);
            if (dbuser == null) {
                errors.reject("NameOrPwdError", "用户名或密码错误!");
                throw new BizException("用户名或密码错误!", errors.getAllErrors());
            }
            return dbuser;
        } else {
            throw new BizException("登录失败!", errors.getAllErrors());
        }
    }

    public User checkName(User user, Errors errors) throws BizException {
        if (errors.hasFieldErrors("name") == false) {
            User dbuser = um.selectByName(user.getName());
            if (dbuser == null) {
                errors.rejectValue("name", "nameError", "用户名错误!");
                throw new BizException("用户名错误!", errors.getAllErrors());
            }
            return dbuser;
        } else {
            throw new BizException("用户名填写错误!", errors.getAllErrors());
        }
    }

    public void resetPwd(User user, Errors errors) throws BizException {
        if (errors.hasFieldErrors("name") == false &&
                errors.hasFieldErrors("pwd") == false) {
            // MD5
            String pwd = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
            user.setPwd(pwd);
            um.updatePwdByName(user);
        } else {
            throw new BizException("重置密码失败!", errors.getAllErrors());
        }
    }
}
